package pl.edu.kassiopeia.repository.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import pl.edu.kassiopeia.repository.exceptions.PluginNotFoundException;
import pl.edu.kassiopeia.repository.model.Plugin;

@Repository("pluginDao")
public class PluginDaoImpl implements PluginDao {
	private final Logger logger = Logger.getLogger(getClass());

	private HibernateTemplate hibernateTemplate;
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
	     hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	@Override
	public void save(Plugin plugin) {
		logger.info("Saving plugin: " + plugin.toString() + "to database");
		hibernateTemplate.save(plugin);
	}

	@Override
	public void update(Plugin plugin) {
		logger.info("Updating plugin: " + plugin.toString() + "in database");
		hibernateTemplate.update(plugin);
	}

	@Override
	public void delete(Plugin plugin) {
		logger.info("Deleting plugin: " + plugin.toString() + "from database");
		hibernateTemplate.delete(plugin);
	}


	@Override
	public List<Plugin> findAll() {
		logger.info("Query for all plugins from database");
		List list = hibernateTemplate.find("from Plugin");
		logger.info("Found: " + list.size() + " plugins");
		return list;
	}

	@Override
	public Plugin findByCoordinates(String groupId,
			String pluginId, String version) throws PluginNotFoundException {
		logger.info("Query for plugin with groupId: " + groupId 
				+ " pluginId: " + pluginId + " version: " + version);
		List list = hibernateTemplate.find(
				"from Plugin where pluginId = ? and groupId=?  and version=?", new Object[] { pluginId, groupId,  version});
		logger.info("Found: " + list.size() + "plugins matching the criteria");
		if(list.size() == 0){
			throw new PluginNotFoundException();
		}
		return (Plugin)list.get(0);
	}

}
